﻿using System.Web.Mvc;
using MvcMall.Core.Commands;
using MvcMall.Core.Contacts.Tasks;
using MvcMall.Framework.Mapper;
using SharpArch.Web.NHibernate;
using System.Linq;
using MvcMall.AdminPortal.Controllers.ArticleCategory.ViewModels;
using System;

namespace MvcMall.AdminPortal.Controllers.ArticleCategory
{
    public class ArticleCategoryController : BaseController
    {
        private readonly IArticleCategoryTask _articleCategoryTask;

        private readonly IMapper<ArticleCategoryModel, ArticleCategoryCommand> _articleCategoryCommandMapper;

        private readonly IMapper<MvcMall.Core.Domains.ArticleCategory, ArticleCategoryModel> _articleCategoryModelMapper;

        public ArticleCategoryController(IArticleCategoryTask articleCategoryTask, IMapper<ArticleCategoryModel, ArticleCategoryCommand> articleCategoryCommandMapper, IMapper<MvcMall.Core.Domains.ArticleCategory, ArticleCategoryModel> articleCategoryModelMapper)
        {
            this._articleCategoryTask = articleCategoryTask;
            this._articleCategoryCommandMapper = articleCategoryCommandMapper;
            this._articleCategoryModelMapper = articleCategoryModelMapper;
        }

        public ActionResult Save(int? menuId)
        {
            if (menuId != null && menuId > 0)
            {
                var articleCategory = _articleCategoryTask.Get(Int32.Parse(menuId.ToString()));
                var viewMode = _articleCategoryModelMapper.MapFrom(articleCategory);
                if (articleCategory == null)
                    return ShowMsg("不存在该类别");
                return View(viewMode);
            }
            return View();
        }


        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(ArticleCategoryModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var dataModel = _articleCategoryCommandMapper.MapFrom(model);
            var domainModel = _articleCategoryTask.Save(dataModel);
            return ShowMsg(domainModel != null ? "保存成功" : "保存失败", Url.Action("Index", "ArticleCategory"));
        }


        public ActionResult Index()
        {
            var listModel = _articleCategoryTask.GetAll().Select(m => new ArticleCategoryModel { CategoryName = m.CategoryName, ArticleCategoryId = m.Id }).ToList();
            return View(listModel);
        }
    }
}
